<template>
  <EcDialog v-model="dialogVisible" :auto-height="true" body-height="540px" class="form-dialog" top="10vh" width="55%">
    <!-- 标题 -->
    <template #title>
      <div class="dialog-title">
        <SvgIcon :icon="dialogIconMap[dialogMode]"/>
        <span>{{ dialogModeMap[dialogMode] + ' - ' + (menuTypeList[formData.type] ? '系统' + menuTypeList[formData.type] : dialogTitle) }}</span>
      </div>
    </template>

    <!-- 表单数据 -->
    <el-form ref="formRef"
             v-loading="dataLoading"
             :disabled="readonly"
             :model="formData"
             :rules="formRules"
             label-width="100px"
             status-icon>

      <el-form-item label="菜单类型：" prop="type">
        <el-radio-group v-model="formData.type" @change="handleChangeMenuType">
          <el-radio v-for="(type, index) in menuTypeList" :key="index" :value="index" border>{{ type }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="menuTypeList[formData.type] + '名称：'" prop="title">
        <el-input v-model="formData.title" :placeholder="'请输入' + menuTypeList[formData.type] + '名称'"></el-input>
      </el-form-item>

      <el-form-item label="上级菜单：" prop="parent_name">
        <TreeSelect ref="menuTreeRef" v-model="formData.parent_name" tree-key="id" :tree-data="menuData" @selectChange="handleTreeIdChange"/>
      </el-form-item>

      <template v-if="formData.type != 2">
        <el-form-item :rules="[{required: true, message: '访问路径不能为空', trigger: 'blur'}]" label="访问路径：" prop="path">
          <el-input v-model="formData.path" placeholder="访问路径"></el-input>
        </el-form-item>

        <el-form-item :rules="[{required: true, message: '菜单组件不能为空', trigger: 'blur'}]" label="菜单组件：" prop="component">
          <el-input v-model="formData.component" placeholder="菜单组件"></el-input>
        </el-form-item>

        <el-form-item label="重定向路径：" prop="redirect">
          <el-input v-model="formData.redirect" placeholder="重定向路径"></el-input>
        </el-form-item>
      </template>

      <template v-if="formData.type == 1">
        <el-form-item :rules="[{required: true, message: '视图名称不能为空', trigger: 'blur'}]" label="视图名称：" prop="name">
          <el-input v-model="formData.name" placeholder="视图名称 用于缓存"></el-input>
        </el-form-item>
      </template>

      <template v-if="formData.type != 0">
        <el-form-item label="授权标识：" prop="permissions">
          <el-input v-model="formData.permissions"
                    :autosize="{ minRows: 2, maxRows: 4}"
                    placeholder="多个用逗号分隔, 如: user:list,user:create" type="textarea"></el-input>
        </el-form-item>
      </template>

      <template v-if="formData.type !== 2">
        <el-row>
          <el-col :md="12">
            <el-form-item label="菜单图标：" prop="icon">
              <IconSelect v-model="formData.icon"/>
            </el-form-item>
          </el-col>
          <el-col :md="12">
            <el-form-item label="显示排序：" prop="sort">
              <el-input-number v-model="formData.sort" :min="0" controls-position="right"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :md="12">
            <el-form-item label="是否隐藏：" prop="hidden">
              <el-radio-group v-model="formData.hidden" size="small">
                <el-radio :value="1" border>隐藏</el-radio>
                <el-radio :value="0" border>显示</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="是否启用：" prop="status">
              <el-radio-group v-model="formData.status" size="small">
                <el-radio :value="1" border>启用</el-radio>
                <el-radio :value="0" border>禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :md="12">
            <el-form-item label="是否缓存：" prop="cache">
              <el-radio-group v-model="formData.cache" size="small">
                <el-radio :value="1" border>开启</el-radio>
                <el-radio :value="0" border>关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
    </el-form>

    <!-- 底部操作区域 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="dataLoading" @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!readonly" v-permission="['sys:menu:create', 'sys:menu:update']" :loading="dataLoading" type="primary" @click="onSubmitForm()">确 定</el-button>
      </span>
    </template>
  </EcDialog>
</template>

<script lang="ts" setup>
import { computed, nextTick, reactive, ref } from 'vue';
import { ElLoading, ElMessage, ElNotification, FormInstance, FormRules } from 'element-plus';
import { EcDialog } from '@/components/dialog';
import {
  getMenuList,
  getMenuAdd,
  SysMenuData,
  getMenuInfo,
  sysMenuSaveOrUpdate,
  sysMenuTreeSelect, getMenuUpdate
} from '@/api/api-sys.ts';
import { IconSelect, SvgIcon } from '@/components/icon';
import { TreeSelect } from '@/components/tree-select';
import useDialog from '@/hooks/use-dialog.ts';

defineOptions({name: 'SysMenuForm'})

const formRef = ref<FormInstance>();
const formLoading = ref(false); // 表单是否加载中
const {dialogVisible, dialogTitle, dialogMode, dialogModeMap, dialogIconMap} = useDialog(false);
const menuTypeList = ['目录', '菜单', '按钮'];

// 默认表单数据
let defaultForm: SysMenuData = {
  id: 0,
  pid: 0,
  parent_name: '',
  title: '',
  name: '',
  icon: '',
  path: '',
  redirect: undefined,
  component: undefined,
  permissions: undefined,
  type: 1,
  hidden: 0,
  cache: 0,
  status: 1,
  sort: 99,
  plat: 'client'
};

// 表单数据
const formData = ref({...defaultForm});

// 表单验证规则
const formRules = reactive<FormRules>({
  name: [{required: true, message: '名称不能为空', trigger: 'change'}],
});

/** 是否只读 */
const readonly = computed(() => {
  return dialogMode.value == 0;
});

/** 是否新增 */
const isCreate = ref();

const menuData = ref<SysMenuData[]>([]);
const menuTreeRef = ref();
const menuTreeLoading = ref(false)
const transformTitles=(array:any,depth=1)=> {
  return array.map(item => ({
    name: item.title,
    id: item.id,
    pid: item.pid,
    child: depth < 2 && item.child
      ? transformTitles(item.child.slice().reverse(), depth + 1)
      : []
  }));
}
const getMenuTreeData = async () => {
  // menuTreeLoading.value = true
  try {
    // const {data} = await sysMenuTreeSelect();
    const {body} = await getMenuList({
      action:'tree',
      plat:'client'
      // cate:'ADMIN_MENU'
    });
    let data=[
      {
        id: 0,
        name:"顶级菜单",
        open:true,
        pid: -1,
        child: transformTitles(body).reverse()
      }
  ]
    menuData.value =data
  } finally {
    menuTreeLoading.value = false
  }
};

/** 判断数据是否处于加载中 */
const dataLoading = computed(() => {
  return formLoading.value || menuTreeLoading.value;
})

/** 打开弹窗 */
const open = async (mode: number, id?: number) => {
  dialogMode.value = mode;
  dialogTitle.value = '系统菜单';
  dialogVisible.value = true;
  // 重置表单
  resetForm();
  isCreate.value=id
  console.log(isCreate.value)
  // 获取权限菜单数据
  await getMenuTreeData();

  // 加载信息
  if (id) {
    formLoading.value = true
    try {
      // 加载数据
      const {body} = await getMenuInfo({id:id,action:'info'})
      formData.value = body;
      handleSetCurrentNode();
    } finally {
      formLoading.value = false
    }
  } else {
    handleSetCurrentNode();
  }
}
// 提供 open 方法，用于打开弹窗
defineExpose({open})

const handleTreeIdChange = (val: any) => {
  console.log(11)
  formData.value.pid = val
};

const handleSetCurrentNode = () => {
  nextTick(() => {
    menuTreeRef.value?.handleSetCurrentNode(formData.value.pid)
  });
};

const handleChangeMenuType = (val: Number) => {
  if (0 == val) {
    if (!formData.value.component) {
      formData.value.redirect = undefined
      formData.value.component = 'Layout'
    }
  } else if ('Layout' == formData.value.component) {
    formData.value.redirect = undefined
    formData.value.component = undefined
  }
  formRef.value?.clearValidate();
};

/** 表单提交 */
const emit = defineEmits(['refresh']);
const onSubmitForm = async () => {
  await formRef.value?.validate((valid, fields) => {
    if (!valid) {
      ElMessage({type: 'error', message: '请检查是否有必填项未完善',});
      return
    }

    const loading = ElLoading.service({
      lock: true,
      text: '正在提交中...',
      background: 'rgba(0, 0, 0, 0.2)'
    })
    // let data={
    //   cate:'ADMIN_MENU',
    //   value:JSON.stringify([formData.value])
    // }
    console.log(formData.value.id)
    if(isCreate.value<=0){
      // formData.value.plat='client'
      getMenuAdd(formData.value,{action:'add'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('refresh')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }else{
      getMenuUpdate(formData.value,{action:'update',plat:'client'}).then(response => {
        // 提示信息
        ElNotification({title: '成功', message: '操作完成', type: 'success', duration: 2000})
        // 发送操作成功的事件
        emit('refresh')
        // 隐藏窗口
        dialogVisible.value = false
      }).finally(() => loading.close())
    }
    // 提交数据

  });
};

/** 重置表单 */
const resetForm = () => {
  // 重置表单数据
  formData.value = {...defaultForm};
  // 重置界面表单数据
  formRef.value?.resetFields();
};

</script>

<style lang="scss" scoped>
.form-dialog {
  .el-input-number {
    max-width: 10rem;
  }
}
</style>
